import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:app/src/http/model/ajaxsales_model.dart';
import 'package:app/src/presenter/review_presenter.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_node_list.dart';
import 'package:app/src/ui/route/works/public/review_details_ui.dart';
import 'package:app/src/ui/route/works/public/review_submitted.dart';

import '../../../../../generated/app_strings.dart';
import '../../../../http/bean/ywx_limit.dart';
import '../../../../manager/audit_manager.dart';
import '../../../dialog/dailog.dart';
import '../../worksdo/type16_material_requisition/public/acom/ui_material_form.dart';
import '../../worksdo/type16_material_requisition/public/items/ui_attachment.dart';
import '../../worksdo/type16_material_requisition/public/items/ui_material.dart';
import '../../worksdo/type16_material_requisition/public/review_submitted_material.dart';
import '../public/image/ui_image_upload.dart';
import 'acom/ui_material_audit_form.dart';
import 'item/ui_export.dart';
import 'item/ui_material_audit.dart';

///请购单审核详情
class MaterialRequisitionAuditDetailsRoute extends StatefulWidget {
  YwxItem item;

  MaterialRequisitionAuditDetailsRoute(this.item);

  @override
  _State createState() => _State();
}

class _State extends State<MaterialRequisitionAuditDetailsRoute> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    presenter.getContractapplygetinfoWithDelay(context); //获取审核详情数据
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    AjaxSalesModel.clear(); //清除物料编码数据缓存；
  }

  @override
  Widget build(BuildContext context) {
    var material = AuditManager.getAuditManager().material;
    // print("=========================================${material?.YwxName}");
    if (material != null && material.YwxName.contains("请购申请")) {
      // print(
      //     "================================================================_body2()");
      return ReviewDetailsUi.build(context, presenter, _body2);
    } else {
      // print(
      //     "================================================================_body()");
      return ReviewDetailsUi.build(context, presenter, _body);
    }
  }

  ///请购单审核
  Widget _body(BuildContext context) {
    if (presenter?.mDatas == null) {
      return AppUi.getEmptyView();
    }
    var mDatas = presenter?.mDatas?.PurDemandInfo;
    var mOldDatas = presenter?.mOldDatas?.PurDemandInfo;

    ///正常请购单审核
    List<Widget> children = [];
    children.add(
        UiMaterialAudit.build(context, mDatas, mOldDatas, setState)); //采购单信息
    children.add(UiMaterialAuditForm.build(context, mDatas, false)); //物料信息
    children.add(UiAttachment.build(context, mDatas?.FilePatchOld,
        isShowEmpty: true)); //附件
    // children.add(UiExport.build(context)); //导出PDF
    children.add(UiNoteList.build(context, presenter?.mDatas?.NodeList)); //审核日志
    return Column(
      children: [
        Expanded(child: UiBase.listView(context, children)),
        Visibility(
            child: ReviewSubmittedStateful(
              presenter?.mDatas,
              hasBack: true,
              onlyBack: false,
              hasEnd: false,
              hasAuditOpinion: true,
              callbackWithT: (subData) {
                //fixme 提交参数数据
                var index = 1; //fixme 加一个序号。服务器需要。
                mDatas?.PurDemandList?.forEach((element) {
                  element.index = index;
                  index++;
                });
                subData.GetCheckPurDemand = mDatas?.PurDemandList;
                // print(
                //     "========================================================入库仓位：${mDatas?.Storehouse}");
                // print(
                //     "========================================================检验员：${mDatas?.Checker}");
                // print(
                //     "========================================================入库仓位：${subData.FLoseApplyInfo?.Storehouse}");
                // print(
                //     "========================================================检验员：${subData.FLoseApplyInfo?.Checker}");
              },
            ),
            visible: presenter?.mDatas != null)
      ],
    );
  }

  ///请购申请
  Widget _body2(BuildContext context) {
    var mDatas = presenter?.mDatas?.PurDemandInfo;
    var mOldDatas = presenter?.mOldDatas?.PurDemandInfo;
    if (mDatas == null) {
      return AppUi.getEmptyView();
    }

    // print("工厂名称${mDatas?.FactoryName}\t${mDatas?.FactoryId}");
    mDatas?.PurDemandList?.forEach((element) {
      if (StringUtils.isEmpty(element.FactoryName)) {
        ///fixme 防止工厂为空。
        element.FactoryName = mDatas.FactoryName;
        element.FactoryId = mDatas.FactoryId;
      }
    });

    var material = AuditManager.getAuditManager().material;
    var IsApproval = material?.IsApproval ?? false;
    List<Widget> children = [];
    children
        .add(UiMaterial.build(context, mDatas, mOldDatas, setState)); //请购单信息
    if (IsApproval) {
      //有申请数量，有批准数量
      children.add(UiMaterialAuditForm.build(context, mDatas, true)); //物料信息
    } else {
      //只有申请数量，没有批准数量
      children.add(UiMaterialForm.build(context, mDatas, true)); //物料信息
    }
    // var isCanoOeration = mDatas?.isCanoOeration() ?? false;
    var isCanoOeration = true; //这里都可以上传图片。
    if (isCanoOeration) {
      children.add(UiImageUpLoad.build(context, mDatas?.getId(),
          title: AppStrings.of(context).UploadEvidence2)); //上传图片
    }
    children.add(
        UiAttachment.build(context, mDatas?.FilePatchOld, isDel: true)); //附件
    // children.add(UiExport.build(context)); //导出PDF
    children.add(UiNoteList.build(context, presenter?.mDatas?.NodeList)); //审核日志
    var onlyBack = mDatas?.isOnlyBack();
    var hasSave = mDatas?.isCanoOeration(); //保存
    var hasSubmit = mDatas?.isCanoOeration(); //提交
    if (IsApproval) {
      //已审核,只能查看
      onlyBack = true; //已审核，不能进行审核操作。
      hasSave = false;
      hasSubmit = false;
    } else {
      //未审核
      onlyBack = false; //已审核，不能进行审核操作。
      hasSave = true;
      hasSubmit = true;
    }
    return Column(
      children: [
        Expanded(child: UiBase.listView(context, children)),
        Visibility(
            child: ReviewSubmittedStateful2(
              presenter?.mDatas,
              hasSave: hasSave,
              //hasSave 保存
              hasSubmit: hasSubmit,
              //hasSubmit 提交
              onlyBack: onlyBack,
              //onlyBack 是否只有一个返回键，其他什么操作都没有。
              callbackWithT: (subData) {
                //fixme 提交参数数据
                subData.purDemand = mDatas;
              },
              callbackWithBoolResult: () {
                //fixme 提交数据格式验证
                if (StringUtils.isEmptyWithNumber(mDatas?.PurEndDate)) {
                  AppDialog.showDialogWithInfo(context,
                      content: AppStrings.of(context)
                          .PurchaseDate5); //fixme 要货日期不能为空
                  return false;
                }
                var i = 1;
                var ii = 1; //fixme 记录第几行
                var b = true;
                mDatas?.PurDemandList?.forEach((element) {
                  //fixme 请购申请，有提交和保存的时候，MinNum和DemandNum赋值一样。
                  //fixme 防止 MinNum与DemandNum不同；物料请购提交服务器使用的申请数量是MinNum这个字段；（请购申请，物料请购时，注意。）
                  element.MinNum = element.DemandNum;
                  if (b && StringUtils.isEmptyWithNumber(element?.DemandNum)) {
                    ii = i;
                    b = false;
                  }
                  i++;
                });
                if (!b) {
                  AppDialog.showDialogWithInfo(context,
                      content: AppStrings.of(context)
                          .NumberOfApplications2(ii)); //fixme 申请数量不能为空
                  return false;
                }
                return true;
              },
            ),
            visible: mDatas != null)
      ],
    );
  }
}

class _Presenter extends ReviewPresenter {}
